#include <string>
#include <iostream>
#include <vector>


using namespace std;


struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(NULL) {}
};



ListNode* getIntersectionNode(ListNode* headA, ListNode* headB)
{
    ListNode* longL = headA, * cur1 = headA;
    ListNode* shortL = headB, * cur2 = headB;
    int l1 = 0, l2 = 0;
    while (cur1)
    {
        l1++;
        cur1 = cur1->next;
    }
    while (cur2)
    {
        l2++;
        cur2 = cur2->next;
    }

    if (l1 < l2)
    {
        shortL = headA;
        longL = headB;
    }
    cur1 = shortL;
    cur2 = longL + abs(l1-l2);
    while (cur1->next != nullptr)
    {
        if (cur1->next == cur2->next)
            return cur1->next;
        cur1 = cur1->next;
        cur2 = cur2->next;
    }
    return nullptr;
}